package com.xykj.enterprise.wechat.ext.api.contacts.department;

import com.xykj.enterprise.wechat.bean.ext.BaseResp;
import com.xykj.enterprise.wechat.ext.service.contacts.ContactsDepartmentService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;


@Function(description = "创建部门", parameters = {
        @Parameter(name = "access_token", type = Type.String, description = "access_token", required = true),

        @Parameter(name = "name", type = Type.String, description = "部门名称。同一个层级的部门名称不能重复。长度限制为1~32个字符，字符不能包括\\:?”<>｜", required = true),
        @Parameter(name = "name_en", type = Type.String, description = "英文名称。同一个层级的部门名称不能重复。需要在管理后台开启多语言支持才能生效。长度限制为1~32个字符，字符不能包括\\:?”<>｜", required = false),
        @Parameter(name = "parentid", type = Type.Integer, description = "父部门id，32位整型", required = true),
        @Parameter(name = "order", type = Type.Integer, description = "在父部门中的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)", required = false),
        @Parameter(name = "id", type = Type.Integer, description = "部门id，32位整型，指定时必须大于1。若不填该参数，将自动生成id", required = false),
})
@Component
@Slf4j
public class CreateDepartment implements Action {

    @Autowired
    private ContactsDepartmentService contactsDepartmentService;

    @Override
    public Response execute(Request request) throws Exception {
        String accessToken = request.getString("access_token");
        log.debug("access_token:{}", accessToken);
        String name = request.getString("name");
        String name_en = request.getString("name_en");
        Integer parentid = request.getInteger("parentid");
        Integer order = request.getInteger("order");
        Integer id = request.getInteger("id");
        if (name == null && parentid == null) {
            return Response.fail("参数错误！");
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("name", name);
        params.put("parentid", parentid);
        if (name_en != null) {
            params.put("name_en", name_en);
        }
        if (order != null) {
            params.put("order", order);
        }
        if (id != null) {
            params.put("id", id);
        }
        BaseResp rsp = contactsDepartmentService.createDepartment(accessToken, params);
        if (rsp.getErrcode() != 0) {
            return Response.fail(rsp.getErrmsg());
        }
        return Response.success();
    }
}
